//
//  XLGHeadImageDownloadQueueInternal.m
//  etionCBLogic
//
//  Created by wjxfhxy on 15-4-30.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "XLGHeadImageDownloadQueueInternal.h"

@implementation XLGHeadImageCache

@synthesize filePath = _filePath;

-(id)initWithContentsOfFile:(NSString *)path
{
    self = [super initWithContentsOfFile:path];
    
    if(self != nil)
    {
        _filePath = [path retain_mm];
    }
    
    return self;
}

-(void)dealloc
{
    [_filePath release_mm];
    superdealloc_mm;
}

@end


@implementation XLGHeadImageDownloadQueueInternal

@synthesize localPath = _localPath;
@synthesize cornerRadius = _cornerRadius;

-(id)init
{
    self = [super init];
    
    _sdm = [[XMSSimpleDownloadManager alloc] initWithDelegate:self];
    
    _dicImageCache = [NSMutableDictionary new];
    
    _cacheLock = [NSLock new];
    
    _cornerRadius = 0;
    
    [self addMainThreadObserverWithDictionarySelector:[NSDictionary dictionaryWithObject:@"observerUIApplicationDidReceiveMemoryWarning:" forKey:UIApplicationDidReceiveMemoryWarningNotification]];
    
    return self;
}

-(void)dealloc
{
    [_cacheLock release_mm];
    [_dicImageCache release_mm];
    [_localPath release_mm];
    [_sdm release_mm];
    superdealloc_mm;
}

-(void)observerUIApplicationDidReceiveMemoryWarning:(NSNotification*)noti
{
    [_dicImageCache removeAllObjects];
}

-(void)terminate
{
    [_sdm terminateAllDownloadTask];
    [self removeObserver];
}

-(void)simpleDownloadManager:(XMSSimpleDownloadManager *)sdm finishedDownload:(CSimpleDownloadTaskTag *)tag
{
    NSMutableDictionary *dic = [[NSMutableDictionary new] autorelease_mm];
    [dic setObject:@"1" forKey:XLGHeadImageDownloadQueueHeadImageDownloadResultResultKey];
    [dic setObject:tag.URL forKey:XLGHeadImageDownloadQueueHeadImageDownloadResultURLKey];
    [dic setObject:tag.filePath forKey:XLGHeadImageDownloadQueueHeadImageDownloadResultPathKey];
    
//    [self operateHeadImage:tag.filePath];
    
    [NSNotificationCenter postNotification:XLGHeadImageDownloadQueueHeadImageDownloadResultNotification object:nil userInfo:dic];
    
    DispatchMainThreadAsync(^
    {
        [_setImageView enumerateImageViewCacheForImageURL:tag.URL block:^(UIImageView *imageView, BOOL *deleteCache)
        {
            UIImage *image = [self setCacheWithHeadImageURL:tag.URL andHeadImagePath:tag.filePath];
            imageView.image = image;
            *deleteCache = YES;
        }];
    });
}

-(XLGHeadImageCache*)setCheckOrStartDownloadHeadImageWhenAddHeadImageURL:(NSString*)headImageURL
{
    XLGHeadImageCache* image = nil;
    
    NSString *URL = headImageURL;
    
    image = [_dicImageCache objectForKey:URL];
    
    if(image == nil)
    {
        NSString *localPath  = [_localPath stringByAppendingPathComponent:[URL lastPathComponent]];
        if([XMSFileHelper isFileExist:localPath] !=YES)
        {
            if([_sdm isContainDownloadURL:URL] != YES)
            {
                [_sdm addDownloadTask:URL path:localPath attachment:nil];
            }
        }
        else
        {
            if(_dicImageCache.count >= 20)
                [_dicImageCache removeAllObjects];
            image = [[[XLGHeadImageCache alloc]initWithContentsOfFile:localPath] autorelease_mm];
            if(image != nil)
                [_dicImageCache setObject:image forKey:URL];
        }
    }
    return image;
}

-(XLGHeadImageCache*)checkOrStartDownloadHeadImageWhenAddHeadImageURL:(NSString*)headImageURL
{
    __block XLGHeadImageCache* image = nil;
    
    if([NSThread isMainThread] == NO)
    {
        [_cacheLock lock:^
        {
            image = [self setCheckOrStartDownloadHeadImageWhenAddHeadImageURL:headImageURL];
        }];
    }
    else
        image = [self setCheckOrStartDownloadHeadImageWhenAddHeadImageURL:headImageURL];
    
    return image;
}

-(BOOL)setOrStartDownloadHeadImageWhenAddHeadImageURL:(NSString*)headImageURL inImageView:(UIImageView*)imageView tag:(NSString*)tag
{
    BOOL(^f)() = ^BOOL()
    {
        XLGHeadImageCache* image = [self setCheckOrStartDownloadHeadImageWhenAddHeadImageURL:headImageURL];
        if(image != nil)
        {
            imageView.image = image;
            return YES;
        }
        else
        {
            if(_setImageView == nil)
                _setImageView = [XLGHeadImageDownloadQueueSetImageViewImage new];
            
            [_setImageView cacheImageView:imageView withImageURL:headImageURL forTag:tag];
            
            return NO;
        }
        return NO;
    };
    
    __block BOOL result = NO;
    
    if([NSThread isMainThread] == NO)
    {
        [_cacheLock lock:^
        {
            result = f();
        }];
    }
    else
        result = f();
    
    return result;
}

-(NSString*)isHeadImageExist:(NSString*)headImageURL
{
    NSString *path = [_localPath stringByAppendingPathComponent:[headImageURL lastPathComponent]];
    if([XMSFileHelper isFileExist:path] !=YES)
    {
        return @"";
    }
    return path;
}

-(XLGHeadImageCache*)setCacheWithHeadImageURL:(NSString*)headImageURL andHeadImagePath:(NSString*)headImagePath
{
    __block XLGHeadImageCache* image = nil;
    XLGHeadImageCache*(^fun)()=^XLGHeadImageCache*
    {
        XLGHeadImageCache* image = _dicImageCache[headImageURL];
        if(image != nil)
            return image;
        
        image = [[[XLGHeadImageCache alloc] initWithContentsOfFile:headImagePath] autorelease_mm];
        if(_dicImageCache.count >= 20)
            [_dicImageCache removeAllObjects];
        [_dicImageCache setObject:image forKey:headImageURL];
        return image;
    };
    if([NSThread isMainThread] == NO)
    {
        [_cacheLock lock:^
        {
            image = fun();
        }];
    }
    else
        image = fun();
    return image;
}

-(XLGHeadImageCache*)checkDownloadHeadImageWithHeadImageURL:(NSString*)headImageURL
{
    if(headImageURL.length <=0 )
        return nil;
    
    __block XLGHeadImageCache* image = nil;
    
    XLGHeadImageCache*(^fun)(NSString* headImageURL) = ^XLGHeadImageCache*(NSString* headImageURL)
    {
        XLGHeadImageCache* image = nil;
        
        NSString *URL = headImageURL;
        
        image = [_dicImageCache objectForKey:URL];
        
        if(image == nil)
        {
            NSString *localPath  = [_localPath stringByAppendingPathComponent:[URL lastPathComponent]];
            if([XMSFileHelper isFileExist:localPath] == YES)
            {
                if(_dicImageCache.count >= 20)
                    [_dicImageCache removeAllObjects];
                image = [[[XLGHeadImageCache alloc]initWithContentsOfFile:localPath] autorelease_mm];
                if(image != nil)
                    [_dicImageCache setObject:image forKey:URL];
            }
        }
        return image;
    };
    
    
    if([NSThread isMainThread] == NO)
    {
        [_cacheLock lock:^
        {
            image = fun(headImageURL);
        }];
    }
    else
        image = fun(headImageURL);
    
    return image;
}

-(void)deleteHeadImage:(NSString*)headImageURL
{
    void(^fun)()=^
    {
        NSString *path = [_localPath stringByAppendingPathComponent:[headImageURL lastPathComponent]];
        [XMSFileHelper deleteFileDir:path];
        [_dicImageCache removeObjectForKey:headImageURL];
    };
    if([NSThread isMainThread] == NO)
    {
        [_cacheLock lock:^
        {
            fun();
        }];
    }
    else
        fun();
}

-(void)deleteAllHeadImage
{
    void(^fun)()=^
    {
        NSArray *arFile = nil;
        [XMSFileHelper isDirEmpty:_localPath containFiles:&arFile];
        for(NSString *s in arFile)
        {
            [XMSFileHelper deleteFileDir:s];
            [_dicImageCache removeObjectForKey:s];
        }
    };
    if([NSThread isMainThread] == NO)
    {
        [_cacheLock lock:^
        {
            fun();
        }];
    }
    else
        fun();
}

-(void)clearAll
{
    [_sdm cancelAllDownloadTask];
    [self deleteAllHeadImage];
}

-(void)clearTag:(NSString*)tag
{
    [_setImageView removeImageViewCacheForTag:tag];
}

-(void)operateHeadImage:(NSString*)imagePath
{
    if(_cornerRadius > 0)
    {
        NSString *path = imagePath;
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        UIBezierPath *bPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, image.size.width, image.size.height) cornerRadius:_cornerRadius];
        
        UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextAddPath(ctx, bPath.CGPath);
        CGContextClip(ctx);
        
        [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
        
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
        NSData *data = UIImagePNGRepresentation(newImage);

        NSString *newName = [NSString stringWithFormat:@"%@_t_.%@",[[path lastPathComponent] stringByDeletingPathExtension],[[path lastPathComponent] pathExtension]];
        NSString *newPath = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:newName];
        (void)newPath;
        [data writeToFile:imagePath atomically:NO];
    }
}

@end

//@interface UIImageView (SetImageURL)
//
//@property(nonatomic,retain) NSString* imgaeURL;
//
//@end
//
//@implementation UIImageView (SetImageURL)
//
//-(void)setImgaeURL:(NSString *)imgaeURL
//{
//    [self setAssociatedRetainNonatomicValue:imgaeURL withKey:"imageURL"];
//}
//
//-(NSString*)imgaeURL
//{
//    return [self associatedValueForKey:"imageURL"];
//}
//
//@end

@implementation XLGHeadImageDownloadQueueSetImageViewImage
{
    NSMutableDictionary *_imageViewCache;
}

-(id)init
{
    self = [super init];
    
    _imageViewCache = [NSMutableDictionary new];
    
    return self;
}

-(void)dealloc
{
    [_imageViewCache release_mm];
    superdealloc_mm;
}

-(void)cacheImageView:(UIImageView*)imageView withImageURL:(NSString*)imageURL forTag:(NSString*)tag
{
    [[imageView retain_mm] autorelease_mm];
    
    NSMutableDictionary *t = _imageViewCache[tag];
    if(t == nil)
    {
        t = [[NSMutableDictionary new] autorelease_mm];
        _imageViewCache[tag] = t;
    }
    
    NSMutableArray *views = t[imageURL];
    if(views == nil)
    {
        views = [[NSMutableArray new] autorelease_mm];
        [views addObject:imageView];
        t[imageURL] = views;
    }
    else
    {
        __block NSString *d = @"";
        [t enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
        {
            NSArray *views = obj;
            if([views containsObject:imageView] == YES)
            {
                if([key isEqualToString:imageURL] != YES)
                    d = key;
                *stop = YES;
            }
        }];

        if(d.length > 0)
        {
            NSMutableArray *views = t[d];
            [views removeObject:imageView];
            if(views.count <= 0)
               [t removeObjectForKey:d];
        }
        
        NSMutableArray *views = t[imageURL];
        if([views containsObject:imageView] == NO)
            [views addObject:imageView];
    }
}

-(void)enumerateImageViewCacheForImageURL:(NSString*)imageURL block:(void(^)(UIImageView *imageView,BOOL *deleteCache))block
{
    [_imageViewCache enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
    {
        NSMutableDictionary *dic = obj;
        [[dic copy] enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
        {
            if([key isEqualToString:imageURL])
            {
                NSMutableArray *views = obj;
                [[views copy] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
                {
                    BOOL deleteCache = NO;
                    block(obj,&deleteCache);
                    if(deleteCache == YES)
                        [views removeObject:obj];
                }];
                *stop = YES;
                
                if(views.count <= 0)
                    [dic removeObjectForKey:key];
            }
        }];
    }];
}

-(void)removeImageViewCacheForTag:(NSString*)tag
{
    [_imageViewCache removeObjectForKey:tag];
}

@end
